import 'package:pacsun/view/task/theme/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import './mediaGrid.dart';

class MediaPickerPage extends StatefulWidget {
  final List<AssetEntity>? initialSelectedPhotos;
  final List<AssetEntity>? initialSelectedVideos;
  final int? taskRecordId;

  const MediaPickerPage({
    Key? key,
    this.initialSelectedPhotos,
    this.initialSelectedVideos,
    this.taskRecordId,
  }) : super(key: key);

  @override
  State<MediaPickerPage> createState() => _MediaPickerPageState();
}

class _MediaPickerPageState extends State<MediaPickerPage> {
  List<AssetEntity> photoList = [];
  List<AssetEntity> videoList = [];
  List<int> selectedPhotoIndexes = [];
  List<int> selectedVideoIndexes = [];
  int maxPhotoSelect = 18;
  int maxVideoSelect = 1;
  int tabIndex = 0;
  bool isLoading = true;
  bool isLoadingMore = false;
  int currentPage = 0;
  final int pageSize = 100;
  AssetPathEntity? album;
  ScrollController photoScrollController = ScrollController();
  int totalCount = 0;

  @override
  void initState() {
    super.initState();
    _fetchAssets();
    photoScrollController.addListener(_onPhotoScroll);
  }

  @override
  void dispose() {
    photoScrollController.dispose();
    super.dispose();
  }

  Future<void> _fetchAssets() async {
    final PermissionState ps = await PhotoManager.requestPermissionExtend();
    if (!ps.isAuth) {
      setState(() => isLoading = false);
      return;
    }
    List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
      type: RequestType.all,
      onlyAll: true,
    );
    if (albums.isNotEmpty) {
      album = albums[0];
      totalCount = await album!.assetCountAsync;
      await _loadMoreAssets();
    } else {
      setState(() => isLoading = false);
    }
  }

  Future<void> _loadMoreAssets() async {
    if (isLoadingMore || album == null) return;
    setState(() => isLoadingMore = true);
    final List<AssetEntity> newAssets =
        await album!.getAssetListPaged(page: currentPage, size: pageSize);
    setState(() {
      photoList.addAll(newAssets.where((e) => e.type == AssetType.image));
      videoList.addAll(newAssets.where((e) => e.type == AssetType.video));
      currentPage++;
      isLoading = false;
      isLoadingMore = false;

      // 恢复之前的选择
      _restorePreviousSelections();
    });
  }

  void _restorePreviousSelections() {
    if (widget.initialSelectedPhotos != null) {
      for (final photo in widget.initialSelectedPhotos!) {
        final index = photoList.indexWhere((p) => p.id == photo.id);
        if (index != -1 && !selectedPhotoIndexes.contains(index)) {
          selectedPhotoIndexes.add(index);
        }
      }
    }

    if (widget.initialSelectedVideos != null) {
      for (final video in widget.initialSelectedVideos!) {
        final index = videoList.indexWhere((v) => v.id == video.id);
        if (index != -1 && !selectedVideoIndexes.contains(index)) {
          selectedVideoIndexes.add(index);
        }
      }
    }
  }

  void _onPhotoScroll() {
    if (photoScrollController.position.pixels >=
            photoScrollController.position.maxScrollExtent - 200 &&
        !isLoadingMore &&
        photoList.length < totalCount) {
      _loadMoreAssets();
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 1,
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.black,
          elevation: 0,
          leading: BackButton(color: Colors.white),
          title: Text('Recent project', style: TextStyle(color: Colors.white)),
          centerTitle: true,
        ),
        body: isLoading
            ? Center(child: CircularProgressIndicator())
            : StatefulBuilder(
                builder: (context, setStateLocal) {
                  // 更新选择逻辑
                  void selectPhoto(int index) {
                    if (selectedPhotoIndexes.contains(index)) {
                      selectedPhotoIndexes.remove(index);
                    } else if (selectedPhotoIndexes.length < maxPhotoSelect) {
                      selectedPhotoIndexes.add(index);
                    }
                    setStateLocal(() {});
                  }

                  return Stack(
                    children: [
                      TabBarView(
                        physics: NeverScrollableScrollPhysics(),
                        children: [
                          // 图片选择
                          MediaGrid(
                            key: ValueKey('photos_${photoList.length}'),
                            mediaList: photoList,
                            selectedIndexes: selectedPhotoIndexes,
                            maxSelect: maxPhotoSelect,
                            isVideo: false,
                            onTap: selectPhoto,
                            scrollController: photoScrollController,
                          ),
                        ],
                      ),
                      // 悬浮的 Next 按钮
                      Positioned(
                        bottom: 16,
                        right: 16,
                        child: SafeArea(
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              shape: StadiumBorder(),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 24, vertical: 12),
                            ),
                            onPressed: () {
                              // 获取选中的照片和视频数据
                              List<AssetEntity> selectedPhotos =
                                  selectedPhotoIndexes
                                      .map((index) => photoList[index])
                                      .toList();
                              Navigator.pop(context, selectedPhotos);
                            },
                            child: Text(
                              'Confirm',
                              style: customTextStyle(fontWeight: 900),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
      ),
    );
  }
}
